﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.WebApi;
using System.Reflection;
using Zero.Data.Repositories;
using Zero.Data.Infrastructure;
using System.Web.Http;
using Zero.Service;

namespace Zero.Web.API
{
    public static class Bootstrapper
    {
        public static void Run()
        {
            SetAutofacWebAPIServices();
        }

        private static void SetAutofacWebAPIServices()
        {
            var configuration = GlobalConfiguration.Configuration;
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerApiRequest();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerApiRequest();
            builder.RegisterType<SystemService>().As<ISystemService>().InstancePerApiRequest();
            builder.RegisterType<UserRepository>().As<IUserRepository>().InstancePerApiRequest();
            builder.RegisterAssemblyTypes(typeof(UserRepository)
                .Assembly).Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerApiRequest();
            builder.RegisterAssemblyTypes(typeof(SystemService)
                .Assembly).Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces().InstancePerApiRequest();
            //var services = Assembly.Load("Zero.Service");
            //builder.RegisterAssemblyTypes(services).Where(t => t.Name.EndsWith("Service"))
            //    .InstancePerApiRequest();
            var container = builder.Build();
            var resolver = new AutofacWebApiDependencyResolver(container);
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }
    }
}